﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MIO.Client.Protocal
{
    public class CharsetHelper
    {
        public const String ENCODE_CHARSET = "UTF-8";
        public const String DECODE_CHARSET = "UTF-8";

        public static String getString(byte[] b, int len)
        {
            try
            {
                Encoding encoding = Encoding.GetEncoding(DECODE_CHARSET);
                return encoding.GetString(b, 0, len);
            }
            catch (DecoderFallbackException e)
            {
                return Encoding.Default.GetString(b,0,len);
            }
        }
        public static String getString(byte[] b, int start, int len)
        {
            try
            {
                Encoding encoding = Encoding.GetEncoding(DECODE_CHARSET);
                return encoding.GetString(b, start, len);
            }
            catch (DecoderFallbackException e)
            {
                return Encoding.Default.GetString(b, start, len);
            }
        }

        public static byte[] getBytes(String str)
        {
            if (str != null)
            {
                try
                {
                    Encoding encoding = Encoding.GetEncoding(DECODE_CHARSET);
                    return encoding.GetBytes(str); 
                }
                catch (DecoderFallbackException e)
                {
                    return Encoding.Default.GetBytes(str);
                }
            }
            else
                return new byte[0];
        }
    }
} 
